package com.swak.frame.api.filter.extension;

import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.base.Splitter;
import com.google.common.collect.Sets;
import com.swak.frame.Version;
import com.swak.frame.config.ConfigCenterAdapter;
import com.swak.frame.context.BoundContext;
import com.swak.frame.extension.annotation.Extension;
import com.swak.frame.extension.provider.WhiteListExtPtProvider;
import com.swak.frame.util.EmptyObject;
import com.swak.frame.util.StringPool;

@Extension(desc = "白名单")
public class DefaultWhiteListProducer implements WhiteListExtPtProvider {

	@Autowired(required = false)
	private ConfigCenterAdapter configCenterAdapter;

	@Override
	public Set<String> getConfig(BoundContext resource) {
		if (configCenterAdapter == null) {
			return EmptyObject.emptySet();
		}
		String whiteList = configCenterAdapter.getString(BIZ_WHITE_LIST_CONFIG);
		if (StringUtils.isEmpty(whiteList)) {
			return EmptyObject.emptySet();
		}
		return Sets.newHashSet(Splitter.on(',').splitToList(whiteList));
	}

	@Override
	public boolean enable(BoundContext resource) {
		boolean enable = enableByVer(resource);
		return enable || configCenterAdapter.getBoolean(WHITE_LIST_ENABLED, false);
	}

	@Override
	public Set<String> getAuthCode(BoundContext resource) {
		String authcode = configCenterAdapter.getString(WHITE_LIST_AUTHCODE);
		if (StringUtils.isEmpty(authcode)) {
			return EmptyObject.emptySet();
		}
		return Sets.newHashSet(Splitter.on(',').splitToList(authcode));
	}

	@Override
	public boolean enableByVer(BoundContext resource) {
		String version = Version.CURRENT.toString();
		return configCenterAdapter.getBoolean(WHITE_LIST_ENABLED + StringPool.UNDERLINE + version, false);
	}
}
